
import { create } from 'zustand';

interface User {
  id: string;
  username: string;
  email: string;
  avatar?: string;
  role: string;
}

interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  loading: boolean;
  error: string | null;
  login: (username: string, password: string) => Promise<void>;
  logout: () => void;
  register: (username: string, email: string, password: string) => Promise<void>;
  clearError: () => void;
}

export const useAuthStore = create<AuthState>((set) => ({
  user: null,
  token: localStorage.getItem('token'),
  isAuthenticated: !!localStorage.getItem('token'),
  loading: false,
  error: null,
  
  login: async (username, password) => {
    set({ loading: true, error: null });
    
    try {
      // 这里模拟登录成功
      const token = 'mock-jwt-token';
      const user = {
        id: '1',
        username,
        email: `${username}@example.com`,
        role: 'admin'
      };
      
      localStorage.setItem('token', token);
      
      set({
        token,
        user,
        isAuthenticated: true,
        loading: false
      });
    } catch (error) {
      set({
        error: '登录失败，请检查用户名和密码',
        loading: false
      });
    }
  },
  
  logout: () => {
    localStorage.removeItem('token');
    set({
      user: null,
      token: null,
      isAuthenticated: false
    });
  },
  
  register: async (username, email, password) => {
    set({ loading: true, error: null });
    
    try {
      // 这里模拟注册成功
      set({ loading: false });
    } catch (error) {
      set({
        error: '注册失败，请稍后重试',
        loading: false
      });
    }
  },
  
  clearError: () => {
    set({ error: null });
  }
})); 